package algorithm_optimal_solution.StackAndQueue;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

//采用了双重递归（重要思想）
public class ReverseStackByRecursive {

    private int getAndRemoveLastElement(Stack<Integer> stack){
        Integer result = stack.pop();
        if(stack.isEmpty()){
            return result;
        }else{
            int lastElement = getAndRemoveLastElement(stack);
            stack.push(result);//将除栈底元素外的其余元素按序放回队列
            return lastElement;
        }
    }

    public void reverseStack(Stack<Integer> stack){
        if(!stack.isEmpty()){
            int lastElement = getAndRemoveLastElement(stack);//移除并返回当前栈底元素
            reverseStack(stack);
            stack.push(lastElement);
        }
    }

    public static void main(String[] args)throws IOException {
        ReverseStackByRecursive main= new ReverseStackByRecursive();
        Stack<Integer> stack=new Stack<>();
        BufferedReader scanner = new BufferedReader(new InputStreamReader(System.in));
        int len = Integer.parseInt(scanner.readLine());
        String value = scanner.readLine();
        String[] result=value.split(" ");
        for(int i=0;i<len;i++){
            stack.push(Integer.parseInt(result[i]));
        }
        main.reverseStack(stack);
        int size = stack.size();
        for(int i=0;i<size;i++){
            System.out.print(stack.pop() + " ");
        }
        scanner.close();
    }
}
